#include "MatlabInterface.h"

#if defined(USE_MATLAB)
	#pragma comment( lib, "libmx"  )
	#pragma comment( lib, "libmex"  )
	#pragma comment( lib, "libmat"  )
	#pragma comment( lib, "libeng"  )
#endif

namespace matlab{

#ifdef USE_MATLAB
#ifdef USE_THREADS
map< boost::thread::id,Engine *> MatlabInterface::eps;
#else
	Engine* MatlabInterface::engine;
#endif
#endif //use matlab

int MatlabInterface::instances = 0;


#ifdef USE_MATLAB
Engine* MatlabInterface::getEngine()
{

#ifdef USE_THREADS
	boost::thread::id id = boost::this_thread::get_id();
	if (eps.find(id) == eps.end())
	{
		//create a new Engine for the current thread
		Engine* ep;
		if (!(ep = engOpen("\0")))
//		if (!(ep = engOpen("ssh nouri@taft \"export DISPLAY=dice.rutgers.edu:0 ; matlab;\"")))
		{
			printf( "\nCan't start MATLAB engine\n");
			return 0;
		}else
		{
			eps[id] = ep;
			return ep;
		}
	}else
		return eps[id];
#else	//no thread
	if (! engine)
	{
		if (!(engine = engOpen("\0")))
		{
			printf( "\nCan't start MATLAB engine\n");
			return 0;
		} else
			return engine;
	}
	else
		return engine;
#endif
}
#endif


MatlabInterface::MatlabInterface(void)
{
/*
#ifdef MATLAB_PLOT
	//start matlab engine if not already started
	if (instances ==0 && !ep)
	{
//		if (!(ep = engOpen("\0")))
		if (!(ep = engOpen("ssh nouri@taft \"export DISPLAY=dice.rutgers.edu:0 ; matlab;\"")))
		{
			printf( "\nCan't start MATLAB engine\n");
			return;
		}
	}
	instances++;
#endif
*/

#ifdef MATLAB_PLOT
	instances++;
#endif
}

void MatlabInterface::closeEngines()
{
#ifdef USE_MATLAB
#ifdef USE_THREADS
	for(map<boost::thread::id, Engine*>::iterator it= eps.begin(); it!= eps.end(); it++)
			engClose((*it).second);
	eps.clear();
#else	//no threading
	engClose(engine);
#endif
	instances  = 0;
#endif
}

MatlabInterface::~MatlabInterface(void)
{
#ifdef USE_MATLAB
	instances--;
	return; //warning:
	closeEngines();
#endif
}
}
